package com.wootion.cims.config.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;




@WebFilter(filterName = "xssFilter", urlPatterns = "/*")
public class XssFilter implements Filter {
    /**
     * 豁免列表
     */
	private List<String> excludeds = new ArrayList<String>();

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		if(handExcluded(req, resp)) {
			chain.doFilter(request, response);
			return;
		}
		XssHttpServletRequestWrapper xssWrapper = new XssHttpServletRequestWrapper(req);
		chain.doFilter(xssWrapper, response);

	}

	private boolean handExcluded(HttpServletRequest req, HttpServletResponse resp) {
		String url = req.getServletPath();
		String method = req.getMethod();
		if(StringUtils.isBlank(url)) {
			return false;
		}
		if(method==null||method.matches("GET")||method.matches("DELETE")) {
			return true;
		}
		for (String s : excludeds) {
			if(url.contains(s)) {
				return true;
			}
		}
		return false;
	}
}
